package com.edu.lxshpc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.edu.lxshpc.pojo.BlogComment;
import com.edu.lxshpc.pojo.User;
import com.edu.lxshpc.povo.BlogCommentVO;
import com.edu.lxshpc.povo.UserVO;
import com.edu.lxshpc.service.BlogCommentService;
import com.edu.lxshpc.mapper.BlogCommentMapper;
import com.edu.lxshpc.utils.PageParams;
import com.edu.lxshpc.utils.PageResult;
import com.edu.lxshpc.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Sanshan
 * @description 针对表【blog_comment】的数据库操作Service实现
 * @createDate 2023-11-26 17:13:04
 */
@Service
@Transactional
@Slf4j
public class BlogCommentServiceImpl extends ServiceImpl<BlogCommentMapper, BlogComment>
        implements BlogCommentService {
    @Autowired
    private BlogCommentMapper blogCommentMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获得博客评论
     * @param blogId 博客id
     * @param pageParams 分页参数
     * @return 分页结果
     */
    @Override
    public Result getBlogComments(Long blogId, PageParams pageParams) {
        if (blogId == null ) {
            return Result.fail("博客id不能为空");
        }
        //1.查询评论
        LambdaQueryWrapper<BlogComment> queryWrapper = new LambdaQueryWrapper<BlogComment>()
                .eq(BlogComment::getBlogId, blogId);
        // 判断是否有分页条件
        Page<BlogComment> blogCommentPage = blogCommentMapper.selectPage(new Page<>(pageParams.getPage(), pageParams.getPageSize()), queryWrapper);
        List<BlogComment> blogComments = blogCommentPage.getRecords();
        //2.为空返回提示
        if (CollUtil.isEmpty(blogComments)) {
            return Result.fail("暂无评论，欢迎评论");
        }
        List<BlogCommentVO> collect = getBlogCommentVOS(blogComments,true);
        PageResult<BlogCommentVO> pageResult = new PageResult<BlogCommentVO>(collect,
                blogCommentPage.getTotal(),
                blogCommentPage.getCurrent(),
                blogCommentPage.getPages(),
                blogCommentPage.getSize());
        return Result.success(pageResult);
    }
    @Override
    public Result getBlogComments(Long blogId) {
        if (blogId == null ) {
            return Result.fail("博客id不能为空");
        }
        //1.查询评论
        LambdaQueryWrapper<BlogComment> queryWrapper = new LambdaQueryWrapper<BlogComment>()
                .eq(BlogComment::getBlogId, blogId);
        // 判断是否有分页条件
        List<BlogComment> blogComments = blogCommentMapper.selectList(queryWrapper);
        //2.为空返回提示
        if (CollUtil.isEmpty(blogComments)) {
            return Result.fail("暂无评论，欢迎评论");
        }
        List<BlogCommentVO> collect = getBlogCommentVOS(blogComments,false);
        PageResult<BlogCommentVO> pageResult = new PageResult<>();
        pageResult.setPages(1L);
        pageResult.setPages(1L);
        pageResult.setRecords(collect);
        pageResult.setCounts(Long.valueOf(collect.size()));
        pageResult.setPageSize(Long.valueOf(collect.size()));
        return Result.success(pageResult);
    }
    /**
     * 获得评论VO
     * @param blogComments 实体类
     * @return 返回VO集合
     */
    private List<BlogCommentVO> getBlogCommentVOS(List<BlogComment> blogComments, boolean flag) {
        // copy vo类
        List<BlogCommentVO> blogCommentVOS = BeanUtil.copyToList(blogComments, BlogCommentVO.class);
        // 遍历查询用户信息
        List<Long> ids = blogComments.stream().map(item -> item.getUserId()).collect(Collectors.toList());
        // copy userVo类
        List<User> userList = Db.lambdaQuery(User.class).select(User::getId, User::getNickname, User::getAvatar, User::getUsername).in(User::getId, ids).list();
        List<UserVO> userVOS = BeanUtil.copyToList(userList, UserVO.class);
        // 循环给评论设置user信息
        blogCommentVOS.stream().forEach(item -> {
            item.setUser(userVOS.stream().filter(ele -> ele.getId().equals(item.getUserId())).findFirst().get());
        });
        if(flag){
            return blogCommentVOS;
        }
        // 分页返回分页结果
        List<BlogCommentVO> collect = blogCommentVOS.stream().filter(item -> item.getParentId().equals(0L)).collect(Collectors.toList());
        collect.stream().forEach(item ->item.setChildren(blogCommentVOS.stream().filter(ele -> ele.getParentId().equals(item.getCommentId())).collect(Collectors.toList())));
        return collect;
    }
    /**
     *  * 插入评论
     * @param blogCommentVO 评论vo类
     * @return 业务信息
     */
    @Override
    public Result saveBlogComment(BlogCommentVO blogCommentVO) {
        BlogComment blogComment = BeanUtil.copyProperties(blogCommentVO, BlogComment.class);

        int insert = blogCommentMapper.insert(blogComment);
        if (insert > 0) {
            return Result.success("评论发表成功");
        }
        return Result.fail("网络繁忙");
    }
    /**
     * 删除评论
     * @param commentId 评论id
     * @return 业务结果信息
     */
    @Override
    public Result removeCommentById(Long commentId) {
        // 先查询评论
        QueryWrapper<BlogComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comment_id",commentId);
        BlogComment blogComment = blogCommentMapper.selectOne(queryWrapper);
        if(BeanUtil.isEmpty(blogComment) ){
            return Result.fail("评论不存在");
        }
        // 再查询子评论
        // 存在子评论
        if(blogComment.getParentId() == 0L){
            // 查子评论id
            QueryWrapper<BlogComment> blogCommentQueryWrapper = new QueryWrapper<>();
            blogCommentQueryWrapper.eq("parent_id",commentId);
            LambdaQueryWrapper<BlogComment> lambdaWrapper = new LambdaQueryWrapper<BlogComment>()
                   .eq(BlogComment::getParentId, commentId);
            List<BlogComment> blogComments = blogCommentMapper.selectList(lambdaWrapper);
            // 获得子评论id集合
            List<Long> collect = blogComments.stream().map(item -> item.getCommentId()).collect(Collectors.toList());
            collect.add(commentId);
            // 批量删除
            int i = baseMapper.deleteBatchIds(collect);
            return i> 0 ? Result.success("删除成功") : Result.fail("删除失败");
        }
        // 不存在子评论，直接删除
        int i = baseMapper.delete(new QueryWrapper<BlogComment>().eq("comment_id",commentId));
        return  i> 0 ?Result.success("删除成功") : Result.fail("删除失败");
    }
}




